package kiwi.assist.dev.guieditor.view {
	import ghostcat.util.core.CallLater;

	import kiwi.assist.dev.guieditor.model.PropertyConfig;
	import kiwi.assist.dev.guieditor.model.UiConfig;
	import kiwi.debug.Log;

	import org.aswing.JTable;
	import org.aswing.VectorListModel;
	import org.aswing.table.PropertyTableModel;
	import org.aswing.table.sorter.TableSorter;

	import flash.display.DisplayObject;
	import flash.utils.getTimer;

	/**
	 * 属性列表
	 * 没什么特别的只是为了包装而已
	 * @author zhangming.luo
	 */
	public class PropertyTable extends JTable {
		private var _uiConfig : UiConfig;
		private var _uiDos : DisplayObject;
		private var model : PropertyTableModel;
		private var listmodel : VectorListModel;
		private var last : Number;

		public function PropertyTable() {
			listmodel = new VectorListModel();
			listmodel.append({key:"1", value:"1"});
			model = new PropertyTableModel(listmodel, ["属性", "值"], ["key", "value"], [null, null]);
			var sorter : TableSorter = new TableSorter(model);
			super(model);
			sorter.setTableHeader(this.getTableHeader());
			sorter.setColumnSortable(2, false);
			model.setColumnEditable(0, false);
			getColumn("值").setCellEditor(new SmartPropertCellEditor());
		}

		public function get uiConfig() : UiConfig {
			return _uiConfig;
		}

		public function set uiConfig(uiConfig : UiConfig) : void {
			if (_uiConfig != uiConfig) {
				_uiConfig = uiConfig;
			}
			CallLater.callLaterNextFrame(onUpdate);
		}

		public function reset() : void {
			listmodel.clear();
		}

		public function updateNow() : void {
			var now : int = getTimer();
			if (now - last < 100) {
				return;
			}
			last = now;
			if (!_uiConfig.instanceMap[_uiDos]) {
				Log.debug(null, "错误了");
				return;
			}
			for (var i : int = 0;i < listmodel.getSize();i++) {
				var elem : * = listmodel.getElementAt(i);
				try {
					PropertyConfig(elem.value).value = _uiDos[elem.key];
				} catch(e : Error) {
					Log.error("无法获取值 " + _uiDos + " : " + elem.key);
				}
			}
			updateUI();
		}

		private function onUpdate() : void {
			listmodel.clear();
			if (uiConfig == null) {
				return;
			}
			for each (var propertyConfig:PropertyConfig in uiConfig.propertyList) {
				if (!_uiDos.hasOwnProperty(propertyConfig.key)) {
					Log.alert("目标ui" + _uiDos + "不存在属性" + propertyConfig.key);
					continue;
				}
				if (propertyConfig.readOnly) {
					continue;
				}
				try {
					propertyConfig.value = _uiDos[propertyConfig.key];
				} catch(e : Error) {
					Log.error("无法获取属性的值 " + _uiDos + " " + propertyConfig.key);
				}
				listmodel.append({key:propertyConfig.key, value:propertyConfig});
			}
		}

		public function get uiDos() : DisplayObject {
			return _uiDos;
		}

		public function set uiDos(uiDos : DisplayObject) : void {
			if (_uiDos != uiDos) {
				_uiDos = uiDos;
			}
			CallLater.callLaterNextFrame(onUpdate);
		}
	}
}
